import java.security.MessageDigest

/**
 * Various utility functions
 * @author dmitryb
 */
class Util {
  public static hexSHA1(String str) {
		MessageDigest hasher = MessageDigest.getInstance('SHA')
    hasher.reset()
		hasher.update(str.getBytes('UTF-8'))
		return (toHex(hasher.digest()))
	}

  public static hexSHA1(File f) {
    MessageDigest hasher = MessageDigest.getInstance("SHA1")
    hasher.reset()

    def buf = new byte[4096]
    def reader = new FileInputStream(f)

    try {
      def bytesRead = reader.read(buf)
      while(bytesRead > 0) {
        hasher.update(buf, 0, bytesRead)
        bytesRead = reader.read(buf)
      }
      toHex(hasher.digest())
    } finally {
      reader.close()
    }
  }

  public static toHex(buf) {
    def result = new StringBuffer()
    for(c in buf) {
      result.append(Integer.toString((c & 0xff) + 0x100, 16).substring(1))
    }
    return result.toString()
  }

  static getCalendar() { Calendar.getInstance(Locale.ROOT) }
  static getCalendar(Date d) { def cal = getCalendar(); cal.setTime(d); cal }

  static getYearMonthDay(Date d) {
    def cal = getCalendar(d)
    [year:cal.get(Calendar.YEAR), month:cal.get(Calendar.MONTH) + 1, day:cal.get(Calendar.DAY_OF_MONTH)]
  }

  static constructRelativeImagePath(int year, int month, int day) {
    [year, month, day].join("/") // Fucking Java insists that Mac only understands ":" as a path separator
  }
}

